import type { App } from "vue";

// 获取组件名，例：SvgIcon下存在组件index.vue,则返回SvgIcon,SvgIcon下存在组件Icon.vue 返回Icon
function getComponentName(key: string) {
  const paths = key.split("/");

  const name = paths
    .filter((it) => !!it && it !== ".")
    .reverse()
    .find(
      (it) =>
        it !== "index.vue" &&
        it !== "index.ts" &&
        it !== "index.tsx" &&
        it !== "index.js" &&
        it !== "index.jsx"
    )
    ?.replace(".vue", "");
  return name ? `${name?.charAt(0)?.toUpperCase()}${name?.slice(1)}` : ""; // 首字母大写
}

// 自动全局注册components下的所有组件
export default function registerComponents(app: App) {
  const components = import.meta.glob("./**/**.{vue,tsx}", {
    eager: true,
  });
  Object.keys(components).forEach((it: string) => {
    const component = components[it] as any;
    app.component(
      component.default.name || getComponentName(it),
      component.default
    );
  });
}
